package com.idearworld.controller;

import static com.idearworld.utils.ControllerUtil.failedResult;
import static com.idearworld.utils.ControllerUtil.successResult;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.idearworld.beans.GlobalConstants;
import com.idearworld.model.Blog;
import com.idearworld.service.BlogService;
import com.idearworld.utils.ControllerUtil;

@Controller
@RequestMapping("/blog")
public class BlogCtrl {
	
	@Autowired
	private BlogService blogService;

	@RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
	@ResponseStatus(HttpStatus.CREATED)
	@ResponseBody
	public Map<String, Object> createBlog(@RequestBody Blog blog,HttpSession session) {
		blog.setUserId(ControllerUtil.getLoginUserId(session));
		blog.setCreateDate(new Date());
		blogService.createBlog(blog);
		if(blog == null){
			return failedResult(GlobalConstants.ERROR_TYPE_ERROR_PARAM,"Error parameter");
		}
		return successResult(blog);
	}
	
	@RequestMapping(value="{id}", method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Map<String, Object> getBlog(@PathVariable( "id" ) final Integer blogId,HttpSession session) {
		return successResult(blogService.getBlogById(blogId));
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Map<String, Object> queryBlog(HttpSession session) {
		List<Blog> blogs=blogService.queryBlog(null);
		return successResult(blogs);
	}

}
